import React from 'react';
import {Form} from 'antd';
import BaseComp from "../Base/BaseComp";
import PropTypes from "prop-types";
import {isEmpty, isFunction, isString} from "lodash-es";
import {compValuePreview} from "../Base/helper/compValuePreview";


/**
 *  链接
 */
export default class LinkComp extends BaseComp {

    static propTypes = {
        ...BaseComp.propTypes,
        compLabel: PropTypes.string,
        metaField: PropTypes.object,
        labelWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
    };

    static defaultProps = {
        labelWidth: 77
    };

    moreCommonProps() {
        return [
            ...super.moreCommonProps(),
            'compLabel', 'metaField', 'labelWidth'
        ];
    }

    componentDidMount() {
        super.componentDidMount();

        // 将此组件的实例保存到 appins 中，用于在被需要时手动控制此组件的逻辑
        const {appins, metaField, customprops} = this.getProps();
        if (appins && metaField && metaField.fieldName && isFunction(appins.setLinkFieldIns)) {
            // 此组件是作为应用的字段使用，则将组件的实例存到 appins.detailLinkFieldInsObj 中，用于按需调用
            appins.setLinkFieldIns(this.fieldName, this, customprops);
        }
    }

    get fieldName() {
        let metaField = this.getPropsByName('metaField');
        if (metaField && isString(metaField.fieldName)) {
            return metaField.fieldName;
        }
        return '';
    }

    mainRender(context) {
        let {compLabel, metaField, labelWidth, style = {}} = this.getProps();

        let labelW = parseInt(labelWidth);
        let tmpStyleO = {
            display: 'inline-block',
            width: isNaN(labelW) ? 'auto' : labelW,
            overflow: 'hidden',
            textOverflow: 'ellipsis'
        };
        compLabel = (
            <span style={tmpStyleO} title={compLabel}>
                    {undefined === compLabel ? this.formatMsgByCn('链接') : compLabel}
            </span>
        );

        return <Form.Item
            label={compLabel}
            name={this.fieldName}
            className={'field-item'}
            style={style}>
            <TxtShow metaField={metaField} formatMsgByCn={this.formatMsgByCn.bind(this)}/>
        </Form.Item>
    };

}

function TxtShow({value, metaField = {}, formatMsgByCn}) {
    let {fieldName, componentType, ...resetFieldProps} = metaField;
    let dataIndex = fieldName;
    let content = compValuePreview(componentType, {
        ...resetFieldProps,
        value,
        dataIndex,
        formatMsgByCn
    });
    return <span className={'form-item-text'} title={content}>{content}</span>
}